#!/bin/bash
set -e

while getopts  "s:p:" opts
do
        case  $opts  in
        s)
                        sample_name=$OPTARG
                        
                ;;
		p)
                        out_prefix=$OPTARG
                        
                ;;
        esac
done
shift $(($OPTIND - 1))





if [ $# -lt 2 ]; then
        echo `basename $0` [-s sample_name] [-p out_prefix] reads1.fq reads2.fq
        exit 1
fi

if [ -z $sample_name ]; then
        sample_name=sap
        
fi

if [ -z $out_prefix ]; then
	out_prefix=1
fi

#-----------------------------------------------
#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------
#-----------------------------------------------

log=.log
if [ ! -e "$log" ]; then
	:> $log
fi

echo Sample name is: $sample_name 2>>$log 1>&2
echo out prefix is: $out_prefix 2>>$log 1>&2



# read_group=@RG\\tID:${sample_name}\\tPL:ILLUMINA\\tSM:$sample_name

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo start bwa aln ... &>$log
bwa aln -t 10 $ref_genome $1 > $out_prefix.1.sai 2>>$log
bwa aln -t 10 $ref_genome $2 > $out_prefix.2.sai 2>>$log
bwa sampe \
-o 10000 \
-P \
-n 6 \
$ref_genome \
$out_prefix.1.sai $out_prefix.2.sai \
$1 $2 \
> $out_prefix.sam \
2>>$log

# -r $read_group \ # it’s a bug?!






# $bwa mem -M -L 1000 -t 10 -R $read_group $ref_genome \
# $1 \
# $2 \
# > $out_prefix.sam \
# 2>> $log

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo 'samtools sam->bam sort index' 2>>$log 1>&2

samtools view -@ 10 -f 1 -F 12 -Sb $out_prefix.sam > $out_prefix.bam 2>> $log

java -jar $picard_path0/AddOrReplaceReadGroups.jar \
I=$out_prefix.bam \
O=$out_prefix.sort.bam \
SO=coordinate \
CREATE_INDEX=true \
SM=$sample_name \
ID=$sample_name \
LB=$sample_name \
PL=illumina \
PU=barcode \
2>>$log

if test ! -f $out_prefix.sort.bam
then
	samtools sort -@ 9 -m 2G -O bam -T $out_prefix $out_prefix.bam > $out_prefix.sort.bam 2>> $log
fi
 
samtools index $out_prefix.sort.bam

